<template>
  <div class="batch-generator">
    <el-card class="generator-card">
      <template #header>
        <div class="card-header">
          <h2>批量生成表情包</h2>
          <p class="subtitle">一次生成多个表情包</p>
        </div>
      </template>

      <!-- 添加提示信息 -->
      <div class="tips">
        <el-alert
          title="由于API限制，每秒最多处理2个请求，批量生成可能需要较长时间"
          type="info"
          :closable="false"
          show-icon
        />
      </div>

      <el-form :model="formData" label-position="top">
        <!-- 文本输入列表 -->
        <div class="text-list">
          <div v-for="(text, index) in formData.texts" :key="index" class="text-item">
            <el-input 
              v-model="formData.texts[index]" 
              :placeholder="getPlaceholder(index)"
              type="textarea"
              :rows="2"
            >
              <template #append>
                <el-button @click="removeText(index)" :disabled="formData.texts.length <= 1">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>

        <el-button @click="addText" type="primary" plain>
          <el-icon><Plus /></el-icon> 添加文本
        </el-button>

        <!-- 风格选择 -->
        <el-form-item label="选择风格">
          <el-select v-model="formData.style" placeholder="请选择风格">
            <el-option label="卡通风格" value="cartoon" />
            <el-option label="写实风格" value="realistic" />
            <el-option label="艺术风格" value="artistic" />
            <el-option label="动漫风格" value="anime" />
            <el-option label="漫画风格" value="comic" />
          </el-select>
        </el-form-item>

        <!-- 修改生成按钮的加载提示 -->
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading"
            @click="handleBatchGenerate"
            :disabled="!formData.texts[0]"
          >
            {{ loading ? `正在生成 (${generatedCount}/${totalCount})` : '开始批量生成' }}
          </el-button>
        </el-form-item>

        <!-- 测试按钮 -->
        <el-form-item>
          <el-button @click="testBatchGenerate" type="warning">
            测试批量生成
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 生成结果 -->
      <div v-if="results.length > 0" class="results-container">
        <h3>生成结果</h3>
        <div class="results-grid">
          <div v-for="(result, index) in results" :key="index" class="result-item">
            <img 
              :src="result.url" 
              :alt="result.text"
              class="result-image" 
              @error="handleImageError(index)"
            />
            <div class="result-text">{{ result.text }}</div>
            <div class="result-actions">
              <el-button type="success" size="small" @click="handleDownload(result.url)">
                <el-icon><Download /></el-icon> 下载
              </el-button>
            </div>
          </div>
        </div>
        <el-button type="primary" @click="handleDownloadAll">
          <el-icon><Download /></el-icon> 下载全部
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Plus, Download } from '@element-plus/icons-vue'
import request from '../utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const generatedCount = ref(0)
const totalCount = ref(0)
const results = ref([])

const formData = reactive({
  texts: [''],
  style: 'cartoon'
})

// 提示词列表
const placeholders = [
  "例如：开心的熊猫",
  "例如：生气的猫咪",
  "例如：惊讶的狗狗",
  "例如：害羞的兔子",
  "例如：困倦的小狗",
  "例如：调皮的小猫",
  "例如：快乐的小鸟",
  "例如：可爱的小象",
  "例如：傲娇的小狐狸",
  "例如：温柔的小羊"
]

// 获取提示词函数
const getPlaceholder = (index) => {
  if (index < placeholders.length) {
    return placeholders[index]
  }
  // 如果超出预设提示词数量，循环使用
  return placeholders[index % placeholders.length]
}

// 添加文本框时使用提示词作为默认值
const addText = () => {
  const newIndex = formData.texts.length
  const placeholder = getPlaceholder(newIndex)
  // 去掉"例如："前缀
  const defaultText = placeholder.replace('例如：', '')
  formData.texts.push(defaultText)
}

const removeText = (index) => {
  formData.texts.splice(index, 1)
}

const handleBatchGenerate = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }

  if (!formData.texts[0]) {
    ElMessage.warning('请至少输入一条文本')
    return
  }

  try {
    loading.value = true
    generatedCount.value = 0
    results.value = []  // 清空之前的结果
    
    // 过滤空文本
    const validTexts = formData.texts.filter(text => text.trim())
    totalCount.value = validTexts.length

    if (validTexts.length === 0) {
      ElMessage.warning('请输入要生成的文本')
      return
    }

    // 每次发送2个文本
    const batchSize = 2
    
    for (let i = 0; i < validTexts.length; i += batchSize) {
      const batch = validTexts.slice(i, i + batchSize)
      try {
        const testData = {
          texts: batch,
          style: formData.style
        }
        
        const response = await request.post('batch/generate', testData)
        console.log('Batch generate response:', response)
        
        if (response.status === 'success') {
          // 处理每个结果，添加完整的 URL
          const newResults = response.data.results.map(result => ({
            url: result.output_url,
            text: result.text,
            loaded: false  // 添加加载状态标记
          }))
          
          console.log('处理后的结果:', newResults)
          
          // 验证 URL 是否有效
          newResults.forEach((result, index) => {
            const img = new Image()
            img.onload = () => {
              result.loaded = true
              console.log(`图片 ${index + 1} 加载成功`)
            }
            img.onerror = () => {
              console.error(`图片 ${index + 1} 加载失败`)
              ElMessage.warning(`第 ${index + 1} 张图片加载失败，请稍后重试`)
            }
            img.src = result.url
          })
          
          results.value.push(...newResults)
          generatedCount.value += response.data.total
          
          ElMessage.success(`第 ${Math.floor(i/batchSize) + 1} 批生成成功`)
        } else {
          console.error('生成失败:', response.data)
          ElMessage.error(`第 ${Math.floor(i/batchSize) + 1} 批生成失败`)
        }
        
        // 等待一小段时间再发送下一批
        if (i + batchSize < validTexts.length) {
          await new Promise(resolve => setTimeout(resolve, 1000))
        }
      } catch (error) {
        console.error('Batch generation error:', error)
        ElMessage.error(`第 ${Math.floor(i/batchSize) + 1} 批生成失败：${error.message}`)
      }
    }

    console.log('最终结果数组:', results.value)  // 添加日志

    if (results.value.length > 0) {
      ElMessage.success(`全部完成！成功生成 ${results.value.length} 个表情包`)
    }
    
  } catch (error) {
    console.error('Batch generation error:', error)
    ElMessage.error('生成失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const handleDownload = (url) => {
  const link = document.createElement('a')
  link.href = url
  link.download = `emoji-${Date.now()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const handleDownloadAll = () => {
  results.value.forEach((result, index) => {
    setTimeout(() => handleDownload(result.url), index * 500)
  })
  ElMessage.success('开始下载全部表情包')
}

const testBatchGenerate = async () => {
  try {
    loading.value = true
    results.value = []  // 清空之前的结果
    
    const testData = {
      texts: [
        "开心的熊猫",
        "生气的猫咪",
        "惊讶的狗狗"
      ],
      style: formData.style
    }
    
    const response = await request.post('batch/generate', testData)
    console.log('Batch generate response:', response)
    
    if (response.data.status === 'success') {
      results.value = response.data.data.results.map(result => ({
        url: result.output_url,
        text: result.text
      }))
      ElMessage.success(`成功生成 ${response.data.data.total} 个表情包`)
    }
  } catch (error) {
    console.error('Test batch generate error:', error)
    ElMessage.error('测试失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const handleImageError = (index) => {
  console.error(`图片加载失败: ${results.value[index].url}`)
  ElMessage.warning(`第 ${index + 1} 张图片加载失败，请稍后重试`)
}
</script>

<style scoped>
.batch-generator {
  max-width: 800px;
  margin: 20px auto;
}

.generator-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin-bottom: 8px;
  color: var(--primary-color);
}

.subtitle {
  color: var(--info-color);
  margin-top: 0;
}

.text-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.text-item {
  display: flex;
  gap: 10px;
}

.results-container {
  margin-top: 30px;
  text-align: center;
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.result-item {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  background: #f5f5f5;
  border-radius: 4px;
}

.result-text {
  font-size: 14px;
  color: #666;
  text-align: center;
  margin: 5px 0;
  word-break: break-all;
}

.result-actions {
  padding: 10px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.tips {
  margin-bottom: 20px;
}
</style>